package ua.soso.ui.dwr.extension;

import org.directwebremoting.extend.Converter;
import org.directwebremoting.impl.DefaultConverterManager;
import org.directwebremoting.util.LocalUtil;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;

public class SpringClassPathConverterManager extends DefaultConverterManager {
    private final PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

    @Override
    public void addConverter(String match, Converter converter) throws IllegalArgumentException {
        if (LocalUtil.hasText(match) && match.endsWith("*") && !match.startsWith("[")) {
            String pattern = "classpath*:" + match.replace('.', '/');
            String packageName = match.substring(0, match.indexOf('*')).replace('.', '/');

            try {
                Resource[] resources = resolver.getResources(pattern);

                for (Resource resource : resources) {
                    String uri = resource.getURI().normalize().toString();

                    String className = uri.substring(uri.lastIndexOf(packageName));

                    if (className.endsWith(".class") && className.indexOf('$') == -1) {
                        className = className.substring(0, className.length() - 6).replace('/', '.');

                        addConverter(className, converter);
                    }
                }
            } catch (IOException e) {
                throw new IllegalArgumentException("Cannot find resources for pattern: " + pattern, e);
            }
        } else {
            super.addConverter(match, converter);
        }
    }
}
